<template>
  <div class="contact-container">
    <van-sticky :offset-top="0.01">

      <van-nav-bar title="联系人"
                   :left-arrow="false">
        <template #right>
          <van-icon name="search"
                    class="left-icon"
                    size="20"
                    color="inherit"
                    @click="navigatorSearch" />

          <!-- 弹框 -->
          <van-popover v-model:show="showPopover"
                       theme="dark"
                       trigger="click"
                       :actions="actions"
                       @select="selectAction"
                       placement="bottom-end">
            <template #reference>
              <van-icon name="add-o"
                        size="20"
                        color="inherit" />
            </template>
          </van-popover>
        </template>
      </van-nav-bar>
    </van-sticky>

    <van-cell is-link
              center
              class="top-cell"
              clickable
              to="/contact/new-friend">
      <!-- 使用 title 插槽来自定义标题 -->
      <template #title>
        <van-icon style="background: orange"
                  name="friends" />
        <span class="custom-title">新的朋友</span>
      </template>
      <!-- 使用 right-icon 插槽来自定义右侧图标 -->
      <template #value>
        <van-badge :content="newContactCount"
                   max="99" />
      </template>
    </van-cell>
    <van-cell is-link
              center
              class="second-cell"
              clickable
              to="/contact/group">
      <!-- 使用 title 插槽来自定义标题 -->
      <template #title>
        <van-icon name="friends" />
        <span class="custom-title">群聊</span>
      </template>
    </van-cell>

    <div class="content">
      <div class="index-bar-content">
        <van-index-bar>
          <div v-for="(item, index) in contactList"
               :key="index">
            <van-index-anchor :index="item.indexAnchor" />
            <van-cell is-link
                      center
                      class="top-cell"
                      clickable
                      @click="navigatorContactInfo(contactInfo.phone)"
                      v-for="(contactInfo, index0) in item.contactInfos"
                      :key="index0">
               <template #title>
                <van-image width="40"
                           height="40"
                           src="https://img.yzcdn.cn/vant/cat.jpeg" />
                <span class="custom-title">{{contactInfo.realName}}</span>
              </template> 
              <template #value>
                <span :style="contactInfo.online === 1? 'color:green;':'color:#dcdee0;'">{{contactInfo.online===1?'在线':'离线'}}</span>
              </template>
                                     
            </van-cell>
          </div>
        </van-index-bar>
        <!-- <div class="bottom-empty">没有数据啦</div> -->
      </div>
    </div>
  </div>
</template>

<script>
// vue3 新特性
import { reactive, toRaw } from "vue";
import * as Pinyin from "jian-pinyin";
import { Toast } from 'vant';

export default {
  data () {

    return {

      // 当前激活的底部tabBar
      active: 1,
      // 左上弹框
      actions: [
        //{ text: "发现", icon: "add-o" },

        { text: "添加好友", icon: "add-o" },
      ],
      // 是否展示左上弹框
      showPopover: false,
      newContactCount: '',
      // 用户列表
      contactList: [],
    };
  },

  methods: {
    // 初始化联系人页面数据
    init () {
      var that = this;
      that.$http
        .get(that.$reqPrefix.user + "/im/users/contact/list", {}).then(res => {
          //获取未处理新朋友的推送消息数量
          that.newContactCount = that.$store.state.imPendingOverview.pendingContactCount === 0 ? '' : that.$store.state.imPendingOverview.pendingContactCount;
          // 渲染该页面
          var obj = that.sortByFirstLetter(res.data)
          for (let key in obj) {
            that.contactList.push({
              "indexAnchor": key,
              "contactInfos": obj[key]
            });
          }

          //构建总线监听
          that.$emitter.on('onmessage', that.onmessage);
        }).catch(err => {
          Toast.fail(err.data.message)
        });
    },
    // 调到搜索页面
    navigatorSearch () {
      this.$router.push("/search");
    },
    // 跳转到联系人页面
    navigatorContactInfo (identity) {
      this.$router.push({ name: "OthersInfo", params: { 'identity': identity } });
    },
    // 将中文数组按首字母分组排序 const origin = ['上饶', '上海','上海', '深圳', '广州', '武汉', '十堰', '天津', '北京']
    /** 结果
     *  {
     *      B: ['北京'],
     *      G: ['广州'],
     *      S: ['上海', '上饶', '深圳', '十堰'],
     *      T: ['天津'],
     *      W: ['武汉']
     *  }
     */
    sortByFirstLetter (origin) {
      /**
       * 先将汉字排序，用到原生的sort方法
       * 这一步是将首字母相同的进行排序， 如 上饶、上海、深圳、十堰都是'S'开头
       * localeCompare
       */
      origin = origin.sort((pre, next) => pre.realName.localeCompare(next.realName));

      /**
       * 构造 Object 用来保存分组排序的数据
       */
      // vue3 写法
      const newObj = reactive({});
      /**
       * 遍历第一轮排序后的数据，按照汉字首字母进行分组
       * Pinyin.getSpell方法用来获取汉字的拼音
       * 默认传一个参数，如果遇到多音字
       * 需要传第二个参数(function)来决定取第几个读音,这里根据具体需求，demo中取的第二个读音
       */
      origin.map((item) => {
        /**
         * 获取汉字的首字母
         * 如果对象中已有key，则push
         * 如果对象中没有这个key，则为这个key构造value，这里value是一个数组
         */
        let key = Pinyin.getSpell(item.realName, (char, spell) => {
          return spell[1];
        })
          .charAt(0)
          .toUpperCase();
        if (Object.prototype.hasOwnProperty.call(newObj, key)) {
          newObj[key].push(item);
        } else {
          newObj[key] = [item];
        }
      });
      return toRaw(newObj);
    },

    //总线回调函数
    onmessage: function (data) {
      // 如果接收到的消息是好友添加，则做相应处理，计数加1
      if (data.messageType === SOCKET_CONSTANT.PACKET.MESSAGE_TYPE.IM_FRIEND_ADD_REQ) {
        // 从缓存中取出来赋值，因为在main.js 中已经进行判断赋值了
        this.newContactCount = this.$store.state.imPendingOverview.pendingContactCount + 1;
      } else if (data.messageType === SOCKET_CONSTANT.PACKET.MESSAGE_TYPE.IM_BROADCAST) {
        var from = data.message.getFrom();
        var content = data.message.getContent();
        if (content === 'online' || content === 'offline') {
          // 遍历现有联系人，进行状态改变
          for (let i = 0, len = this.contactList.length; i < len; i++) {
            var contactInfos = this.contactList[i].contactInfos;
            for (let j = 0, len0 = contactInfos.length; j < len0; j++) {
              if (contactInfos[j].phone === from) {
                this.contactList[i].contactInfos[j].online = content === 'online' ? 1 : 0;
                break;
              }
            }
          }
        }
      }
    },

    //点击选项的时候触发该方法，进行处理
    selectAction (action, index) {
      if (index === 0 && action.text === '添加好友') {
        this.$router.push('/contact/add');
      }
    },


  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created () {
    // 发送初始化请求
    this.init();

  },
  //生命周期 - 销毁完成
  unmounted () {
    //销毁监听
    this.$emitter.off('onmessage', this.onmessage);
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.contact-container {
  position: absolute;
  height: 100%;
  width: 100%;
  background: whitesmoke;
}
.bottom-empty {
  text-align: center;
  height: 2rem;
  color: #969799;
}

.title-span {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
}
.title-margin {
  text-align: center;
}
.left-icon {
  margin-right: 20px;
}
/*reset*/
.van-icon-friends {
  color: #fff;
  background: #23b32f;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 40px;
  width: 40px;
  border-radius: 5px;
  font-size: 24px;
}

.top-cell /deep/ .van-cell__title {
  display: flex;
  align-items: center;
}
.second-cell /deep/ .van-cell__title {
  display: flex;
  align-items: center;
}
.custom-title {
  display: inline-flex;
  align-items: center;
  height: 100%;
  margin-left: 10px;
}
.right-value {
  color: green;
}
</style>
